import { useEffect, useRef, useState } from "react";
import ProForm, {
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormTreeSelect,
  ProFormList,
} from "@ant-design/pro-form";
import ProCard from "@ant-design/pro-card";
import { message, Cascader, Col } from "antd";
import { LeftOutlined } from "@ant-design/icons";
import UploadFile from "@/components/UploadFile";
import { add, update, fetchInfo } from "@/api/per";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import { useLocation, history } from "umi";
import Editor from "@/components/Editor";
import SpecTables from "@/components/SpecTables";
import { fetchList as fetchTemplateList } from "@/api/freeTemplate";


export default () => {
  const location = useLocation();
  const { id } = location.query;
  const title = id ? "编辑商品" : "新增商品";
  const formRef = useRef();
  const [freeTemplateList, setFreeTemplateList] = useState([]);


  const getInfo = async () => {
    const res = await fetchInfo({ id: id });
    console.log("res===", res);
    if (res.data) {
      const postData = {
        ...res.data,
        specification: res.data.specificationVOS || [],
      };
      formRef.current.setFieldsValue(postData);
    }
  };

  const getFreeTemplateList = async () => {
    const res = await fetchTemplateList({
      pageNum: 1,
      pageSize: 999999,
    });
    if (res.data) {
      setFreeTemplateList(res.data);
    }
  };

  const defaultData = {
    name: "儿童电话手表",
    picture:
      "https://linkstar.oss-cn-chengdu.aliyuncs.com/admin/banner66115e29a4f0ffa31e0915aa.jpg",
    specification: [
      {
        id: Date.now(),
        specification: "一个",
        costPrice: 1,
        inventory: 2,
        commodityNum: "3",
        price: 4,
        vipPrice: 5,
        weight: 6,
        volume: 7,
      },
      {
        id: 2,
        specification: "两个",
        costPrice: 10,
        inventory: 20,
        commodityNum: "30",
        price: 40,
        vipPrice: 50,
        weight: 60,
        volume: 70,
      },
    ],
    peripheryInfo: "详情",
  };

  useEffect(() => {
    // formRef.current.setFieldsValue(defaultData);
    getFreeTemplateList();
    if (id) {
      getInfo();
    }
  }, []);

  const handleAddOrUpdate = async (fields) => {
    const postData = {
      ...fields,
      id,
    };
    let func = add;
    if (id) {
      func = update;
    }
    const res = await func(postData);
    if (res.code == 200) {
      message.success(title + "成功");
      history.goBack();
    }
  };

  return (
    <PageContainer
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            {title}
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProForm
        layout="horizontal"
        formRef={formRef}
        onFinish={async (values) => {
          return handleAddOrUpdate(values);
        }}
        submitter={{
          render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
        }}
        labelCol={{
          span: 2,
        }}
      >
        <ProCard title="基础信息" bordered>
          <ProFormText
            width="lg"
            label="商品名称"
            name="name"
            rules={[
              { required: true, message: "请输入商品名称" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />

          <ProFormSelect
            width="lg"
            name="freeTemplateId"
            label="运费模板"
            allowClear
            fieldProps={{
              options: freeTemplateList,
              fieldNames: {
                label: "tempName",
                value: "id",
              },
            }}
            rules={[{ required: true, message: "请选择运费模板" }]}
          />

          <ProForm.Item
            name="picture"
            label="商品图片"
            rules={[{ required: true, message: "请上传图片" }]}
          >
            <UploadFile maxCount={1} />
          </ProForm.Item>

          <ProForm.Item
            name="specification"
            label="规格"
            rules={[{ required: true, message: "请设置规格" }]}
          >
            <SpecTables name="specification"/>
          </ProForm.Item>

          <ProForm.Item
            label="商品详情"
            name="peripheryInfo"
            rules={[{ required: true, message: "请设置商品详情" }]}
          >
            <Editor />
          </ProForm.Item>
        </ProCard>
      </ProForm>
    </PageContainer>
  );
};
